//
//  OrderEnsureViewController.m
//  SXH
//
//  Created by Jack on 15/9/9.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "OrderEnsureViewController.h"
#import "UIButton+WebCache.h"
#import "LPEntity.h"
#import "OrderEntity.h"
#import "OrderProductEntity.h"
#import "OrderViewController.h"
#import "AddressViewController.h"
#import "UserAddressEntity.h"
#import "CommonService.h"
#import "AddAddressViewController.h"
#import "ALiPay.h"
#import "WXPay.h"
#import "CalendarHomeViewController.h"
#import "CalendarViewController.h"
#import "Color.h"
#import "TicketPersonViewController.h"
#import "WebViewController.h"
#import "CouponViewController.h"
#import "MEPopView.h"

@interface OrderEnsureViewController ()<UIPickerViewDelegate, UITextFieldDelegate,UIPickerViewDataSource>  {
    NSArray *pickerArray;
    CalendarHomeViewController *chvc;
    NSString *pickerViewRow;
    int startToEndDays;
    NSString *startDate;
}

@property (weak, nonatomic) IBOutlet UILabel *storeName;
@property (weak, nonatomic) IBOutlet UIButton *productImage;
@property (weak, nonatomic) IBOutlet UILabel *productName;
@property (weak, nonatomic) IBOutlet UILabel *introduce;
@property (weak, nonatomic) IBOutlet UILabel *price;
@property (weak, nonatomic) IBOutlet UIButton *btnALiPay;
@property (weak, nonatomic) IBOutlet UIButton *btnWeiXin;
@property (nonatomic, strong) NSMutableArray *mutableArrayAddress;
@property (weak, nonatomic) IBOutlet UILabel *total;
@property (weak, nonatomic) IBOutlet UILabel *shipCost;
@property (weak, nonatomic) IBOutlet UIView *payWayView;
@property NSString *payWay;
@property (retain, nonatomic) IBOutlet UILabel *logisticsName;
@property (strong, nonatomic) IBOutlet UILabel *productClass;
@property (weak, nonatomic) IBOutlet UILabel *labQty;
@property (weak, nonatomic) IBOutlet UIButton *btnPlus;
@property (weak, nonatomic) IBOutlet UIButton *btnMinus;

@property (retain, nonatomic) UIPickerView *logisticsPicker;

@property (strong, nonatomic) IBOutlet UIView *ensureOrderView1;
@property (strong, nonatomic) IBOutlet UIView *ensureOrderView2;
@property (weak, nonatomic) IBOutlet UILabel *storeName2;
@property (weak, nonatomic) IBOutlet UIButton *productImage2;
@property (weak, nonatomic) IBOutlet UILabel *productName2;
@property (weak, nonatomic) IBOutlet UILabel *introduce2;
@property (weak, nonatomic) IBOutlet UILabel *price2;
@property (weak, nonatomic) IBOutlet UILabel *originPrice2;
@property (weak, nonatomic) IBOutlet UILabel *labQty2;
@property (weak, nonatomic) IBOutlet UIButton *btnPlus2;
@property (weak, nonatomic) IBOutlet UIButton *btnMinus2;
@property (weak, nonatomic) IBOutlet UILabel *outOfDate;
@property (weak, nonatomic) IBOutlet UIButton *btnALiPay2;
@property (weak, nonatomic) IBOutlet UIButton *btnWeiXin2;
@property (weak, nonatomic) IBOutlet UILabel *total2;

@end

@implementation OrderEnsureViewController
@synthesize storeName,productName,introduce,price,total,shipCost,labQty;
@synthesize lpEntity,tDetailsEntity,userEntity;
@synthesize productImage,btnALiPay,btnWeiXin,btnPlus,btnMinus;
@synthesize mutableArrayAddress;
@synthesize addName,addPhone,addressInfo,logisticsName,productClass;
@synthesize payWayView;
@synthesize logisticsPicker;
@synthesize ensureOrderView1,ensureOrderView2;
@synthesize storeName2,productImage2,productName2,introduce2,price2,originPrice2,labQty2,btnPlus2,btnMinus2,outOfDate,ticketPerson,btnALiPay2,btnWeiXin2,total2;
@synthesize productEntity,ticketPersonEntity;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePayResult:) name:@"ORDER_PAY_NOTIFICATION" object:nil];//监听一个通知
    
    if(productEntity){
        _payWay = @"1";
        [self.view addSubview:ensureOrderView2];
        NSString *url = [NSString stringWithFormat:@"%@", productEntity.album_thumb];
        [productImage2 sd_setImageWithURL:[NSURL URLWithString:url] forState:UIControlStateNormal];
        storeName2.text = @"扬州乐游山水网络科技有限公司";
        productName2.text = productEntity.product_title;
        introduce2.text = productEntity.descriptionInfo;
        price2.text = [NSString stringWithFormat:@"¥ %@", productEntity.sale_price];
        originPrice2.text = [NSString stringWithFormat:@"¥ %@", productEntity.old_price];
        total2.text = productEntity.sale_price;
        outOfDate.text = @"日期";
        
        [btnPlus2.layer setCornerRadius:0.0]; //设置矩形四个圆角半径
        [btnPlus2.layer setBorderWidth:1.0]; //边框宽度
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.9, 0.9, 0.9, 1 });
        [btnPlus2.layer setBorderColor:colorref];//边框颜色
        [btnMinus2.layer setCornerRadius:0.0]; //设置矩形四个圆角半径
        [btnMinus2.layer setBorderWidth:1.0]; //边框宽度
        [btnMinus2.layer setBorderColor:colorref];//边框颜色
        [labQty2.layer setCornerRadius:0.0]; //设置矩形四个圆角半径
        [labQty2.layer setBorderWidth:1.0]; //边框宽度
        [labQty2.layer setBorderColor:colorref];//边框颜色
        
        //计算门票剩余天数
        NSDateFormatter * dateFormat = [[NSDateFormatter alloc]init];
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *startdate =[dateFormat dateFromString:productEntity.use_start_date];
        NSDate *enddate =[dateFormat dateFromString:productEntity.use_end_date];
        NSDate *nowDate = [NSDate date];
        double dd = 365.f;
        if(([nowDate timeIntervalSince1970] - [startdate timeIntervalSince1970])>0){
             startDate=@"";
             dd = (double)[enddate timeIntervalSince1970] - [nowDate timeIntervalSince1970];
        }else{
            startDate=productEntity.use_start_date;
            dd = (double)[enddate timeIntervalSince1970] - [startdate timeIntervalSince1970];
        }
        startToEndDays = ceil(dd/86400);
       
    }else{
        mutableArrayAddress = [[NSMutableArray alloc]init];
        [self getAddressDefault];
        _payWay = @"1";
        
        [self.view addSubview:ensureOrderView1];
        
        if(lpEntity){
            NSString *url = [NSString stringWithFormat:@"%@/%@", IMAGE_URL, lpEntity.album_thumb];
            [productImage sd_setImageWithURL:[NSURL URLWithString:url] forState:UIControlStateNormal];
            storeName.text = lpEntity.store_name;
            productName.text = lpEntity.title;
            introduce.text = lpEntity.content;
            //    introduce.text = lpEntity.product_introduce;
            price.text = lpEntity.price;
            total.text = [NSString stringWithFormat:@"%.2f",[lpEntity.price floatValue]+[lpEntity.ship_cost floatValue]];
            shipCost.text = [NSString stringWithFormat:@"(含运费¥%@%@",lpEntity.ship_cost,@")"];
            productClass.text =@"配送方式";
            logisticsName.text = @"快递";
        }else{
            NSString *url = [NSString stringWithFormat:@"%@", tDetailsEntity.album_thumb];
            [productImage sd_setImageWithURL:[NSURL URLWithString:url] forState:UIControlStateNormal];
            storeName.text = tDetailsEntity.a_name;
            productName.text = tDetailsEntity.t_name;
            introduce.text = @"t_preview";//t_preview为空
            price.text = tDetailsEntity.t_price;
            total.text = [NSString stringWithFormat:@"1.00"];
            shipCost.text = [NSString stringWithFormat:@"(含运费¥0.00)"];
            productClass.text =@"出行日期";
            logisticsName.text = @"日期";
        }
        
        [self initPickerView];
        
        [btnPlus.layer setCornerRadius:0.0]; //设置矩形四个圆角半径
        [btnPlus.layer setBorderWidth:1.0]; //边框宽度
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.9, 0.9, 0.9, 1 });
        [btnPlus.layer setBorderColor:colorref];//边框颜色
        [btnMinus.layer setCornerRadius:0.0]; //设置矩形四个圆角半径
        [btnMinus.layer setBorderWidth:1.0]; //边框宽度
        [btnMinus.layer setBorderColor:colorref];//边框颜色
        [labQty.layer setCornerRadius:0.0]; //设置矩形四个圆角半径
        [labQty.layer setBorderWidth:1.0]; //边框宽度
        [labQty.layer setBorderColor:colorref];//边框颜色
    }
}

-(void)initPickerView{
    pickerArray = [NSArray arrayWithObjects:@"顺丰",@"申通",@"韵达",@"圆通",@"天天",@"全峰",@"中通",@"百世汇通",@"自提", nil];
    logisticsPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 180)];
    logisticsPicker.delegate = self;
    logisticsPicker.dataSource = self;
    [logisticsPicker setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:logisticsPicker];
    [self.view bringSubviewToFront:logisticsPicker];
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [pickerArray count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [pickerArray objectAtIndex:row];
}
//点击空白隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    [self inView];
}
- (void)popView {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位秒，浮点数
    [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    self.logisticsPicker.frame = CGRectMake(0, ScreenHeight-180, SCREEN_WIDTH, 180);
    
    [UIView setAnimationDelegate:self];
    // 动画完毕后调用animationFinished
//    [UIView setAnimationDidStopSelector:@selector(animationFinished)];
    [UIView commitAnimations];
}

- (void)inView {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.6];//动画时间长度，单位秒，浮点数
    self.logisticsPicker.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 180);
    
    [UIView setAnimationDelegate:self];
    // 动画完毕后调用animationFinished
//    [UIView setAnimationDidStopSelector:@selector(animationFinished)];
    [UIView commitAnimations];
}
-(void)animationFinished{
    NSLog(@"动画结束!");
}
-(IBAction)logisticsPickerBtn:(id)sender{
    if(productEntity){
//        chvc = [[CalendarHomeViewController alloc]init];
//        chvc.calendartitle = @"出行日期";
//        int days = startToEndDays;
//        [chvc setDays:days startDateforString:startDate orderLastTime:productEntity.order_last_time];//初始化方法
//        chvc.calendarblock = ^(CalendarDayModel *model){
//            outOfDate.text = [model toString];
//        };
//        [self.navigationController pushViewController:chvc animated:YES];
        UIDatePicker * _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 70, 160)];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        CGAffineTransform rotate = CGAffineTransformMakeRotation(0);
        rotate = CGAffineTransformScale(rotate, 0.796, 0.796);
        CGAffineTransform t0 = CGAffineTransformMakeTranslation(-32.5, -22);
        _datePicker.transform = CGAffineTransformConcat(rotate,t0);
        MEPopView * _datePopView = [[MEPopView alloc] initWithTitle:@"选择时间" saveTitle:@"保存"  cancelTitle:@"取消" height:172];
        [_datePopView setTouchOtherHide:NO];
        [_datePopView setContentBlackColor:[UIColor whiteColor]];
        [_datePopView.contentView addSubview:_datePicker];
        [_datePopView show:YES];
        [_datePopView setSaveblock:^(MEPopView *view) {
            outOfDate.text = [[NSDate new] stringFromDate:_datePicker.date];
            [view hide:YES];
        } cancelBlock:^(MEPopView *view) {
            [view hide:YES];
        }];

    }else{
        if(lpEntity){
            [self.view endEditing:YES];
            [self popView];
        }else{
            chvc = [[CalendarHomeViewController alloc]init];
            chvc.calendartitle = @"出行日期";
//            [chvc setAirPlaneToDay:365 ToDateforString:nil];//初始化方法
            chvc.calendarblock = ^(CalendarDayModel *model){
                logisticsName.text = [model toString];
            };
            [self.navigationController pushViewController:chvc animated:YES];
        }
    }
}
//当你选中pickerview的某行时会调用该函数。
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSLog(@"You select row %ld",(long)row);
    logisticsName.text = [pickerArray objectAtIndex:row];
    pickerViewRow =[NSString stringWithFormat:@"%d",(int)row+1];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)btnALiPayAction:(id)sender{
    if(productEntity){
        if(!btnALiPay2.selected){
            btnWeiXin2.selected = false;
            btnALiPay2.selected = true;
            _payWay = @"1";
        }
        [btnALiPay2 setImage:[UIImage imageNamed:K_trade_OK_imageName] forState:UIControlStateSelected];
        [btnWeiXin2 setImage:[UIImage imageNamed:K_trade_default_imageName] forState:UIControlStateNormal];
    }else{
        if(!btnALiPay.selected){
            btnWeiXin.selected = false;
            btnALiPay.selected = true;
            _payWay = @"1";
        }
        [btnALiPay setImage:[UIImage imageNamed:K_trade_OK_imageName] forState:UIControlStateSelected];
        [btnWeiXin setImage:[UIImage imageNamed:K_trade_default_imageName] forState:UIControlStateNormal];
    }
}
- (IBAction)btnWeiXinAction:(id)sender{
    if(productEntity){
        if(!btnWeiXin2.selected){
            btnALiPay2.selected = false;
            btnWeiXin2.selected = true;
            _payWay = @"2";
        }
        [btnWeiXin2 setImage:[UIImage imageNamed:K_trade_OK_imageName] forState:UIControlStateSelected];
        [btnALiPay2 setImage:[UIImage imageNamed:K_trade_default_imageName] forState:UIControlStateNormal];
    }else{
        if(!btnWeiXin.selected){
            btnALiPay.selected = false;
            btnWeiXin.selected = true;
            _payWay = @"2";
        }
        [btnWeiXin setImage:[UIImage imageNamed:K_trade_OK_imageName] forState:UIControlStateSelected];
        [btnALiPay setImage:[UIImage imageNamed:K_trade_default_imageName] forState:UIControlStateNormal];
    }
//    ALERT_ERR_MSG(@"此功能正在开发中");
}

//提交订单
- (IBAction)postOrder:(id)sender{
    if([logisticsName.text isEqualToString:@"快递"]){
        ALERT_ERR_MSG(@"请选择配送方式");
        return;
    }
    if([logisticsName.text isEqualToString:@"日期"]){
        ALERT_ERR_MSG(@"请选出行日期");
        return;
    }
    
    [super showLoadingView:YES];
    
    CommonService *service = [[CommonService alloc] init];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithDictionary:(lpEntity)?[NSDictionary dictionaryWithObjectsAndKeys:
                            @"1", @"phone_type",
                            @"0", @"park_id",
                            userEntity.userId, @"user_id",
                            lpEntity.product_class_id, @"product_class_id",
                           lpEntity.ID,@"product_id",
                           labQty.text,@"qty",
                           pickerViewRow,@"ship_class",
//                           lpEntity.price,@"price",
//                           @"2",@"product_class",
                           _payWay,@"pay_type",
                           _addressID,@"address_id",
                                      nil]:[NSDictionary dictionaryWithObjectsAndKeys:
                                            userEntity.userId, @"userid",
                                            tDetailsEntity.t_id,@"product_id",
                                            labQty.text,@"qty",
                                            logisticsName.text,@"departure_date",
                                            tDetailsEntity.t_price,@"price",
                                            @"1",@"product_class",
                                            _payWay,@"pay_type",
                                            _addressID,@"address_id",
                                            nil] ];
    if (_couponModel) {
        [param setObject:_couponModel.id forKey:@"coupon_user_id"];
    }
    
    [service getNetWorkData:param
                       Path:USER_ORDER_NEW_CREATE
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSString *code = [dic objectForKey:@"code"];
                      [super showLoadingView:NO];
                      dispatch_async(dispatch_get_main_queue(), ^{
                          if([code intValue]==0){
                              //TODO: 保存订单号
                              [self orderInfo:[dic objectForKey:@"order_id"]qty:labQty.text];
                              if(btnALiPay.selected){
                                  //TODO:支付宝创建订单
                                  ALiPay *alipay=[[ALiPay alloc]init];
                                  float _total_amount = [[NSString stringWithFormat:@"%@",[dic objectForKey:@"real_total_amount"]] floatValue];
                                  [alipay postOrder:[dic objectForKey:@"order_num"] productName:AppName productDescription:OrderSubmit amount:[NSString stringWithFormat:@"%.2f",_total_amount] VC:self  orderFlag:@"old"];
                              }else if(btnWeiXin.selected){
                                  //TODO:微信创建订单
                                  WXPay *wxPay=[[WXPay alloc]init];
                                  //本地处理签名
//                                  [wxPay sendPay:[dic objectForKey:@"order_num"] productName:@"乐游山水" amount:@"1" VC:self];
                                  //服务器端处理签名
                                  [wxPay sendPay:dic VC:self];
                              }
                          }else{
                              ALERT_ERR_MSG([dic objectForKey:@"msg"]);
                          }
                      });
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [super showLoadingView:NO];
                      DebugLog(@"%@", message);
                  }];
}

//票务订单提交
- (IBAction)ticketOrderPost:(id)sender{
    if([outOfDate.text isEqualToString:@"日期"]){
        ALERT_ERR_MSG(@"请选出行日期");
        return;
    }
    if([ticketPerson.text isEqualToString:@"添加取票人"]){
        ALERT_ERR_MSG(@"您还没有添加取票人！");
        return;
    }
    [super showLoadingView:YES];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @"1",@"phone_type",
                                      PARK_ID,@"park_id",
                                      userEntity.userId, @"user_id",
                                      productEntity.product_class_id,@"product_class_id",
                                      productEntity.product_id,@"product_id",
                                      labQty2.text,@"qty",
                                      _payWay,@"pay_type",
                                      outOfDate.text,@"departure_date",
                                      ticketPersonEntity.name,@"ota_nickname",
                                      ticketPersonEntity.phone,@"ota_phone",
                                      ticketPersonEntity.uniqueID,@"ota_idno",
                                      nil];
    
    [service getNetWorkData:param
                       Path:TICKET_ORDER_POST
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSString *code = [dic objectForKey:@"code"];
                      [super showLoadingView:NO];
                      dispatch_async(dispatch_get_main_queue(), ^{
                          if([code intValue]==0){
                              //TODO: 保存订单号
                              [self orderInfo:[dic objectForKey:@"order_id"]qty:labQty2.text];
                              if(btnALiPay2.selected){
                                  //TODO:支付宝创建订单
                                  ALiPay *alipay=[[ALiPay alloc]init];
                                  float _total_amount = [[NSString stringWithFormat:@"%@",[dic objectForKey:@"total_amount"]] floatValue];
                                  [alipay postOrder:[dic objectForKey:@"order_num"] productName:AppName productDescription:OrderSubmit amount:[NSString stringWithFormat:@"%.2f",_total_amount] VC:self orderFlag:@"new"];
                              }else if(btnWeiXin2.selected){
                                  //TODO:微信创建订单
                                  WXPay *wxPay=[[WXPay alloc]init];
                                  //本地处理签名
                                  //                                  [wxPay sendPay:[dic objectForKey:@"order_num"] productName:@"乐游山水" amount:@"1" VC:self];
                                  //服务器端处理签名
                                  [wxPay sendPay:dic VC:self];
                              }
                          }else{
                              ALERT_ERR_MSG([dic objectForKey:@"msg"]);
                          }
                      });
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                      [super showLoadingView:NO];
                  }];
}

-(void)orderInfo:(NSString*)order_num qty:(NSString*)qty{
    OrderProductEntity *orderProductEntity = [[OrderProductEntity alloc] init];
    OrderEntity *orderEntity = [[OrderEntity alloc]init];
    if(productEntity){
        orderProductEntity.product_class = @"3";
        orderProductEntity.product_id = productEntity.product_id;
        orderProductEntity.product_name = productEntity.product_title;
        orderProductEntity.price = productEntity.sale_price;
        orderProductEntity.introduce = productEntity.descriptionInfo;
        orderProductEntity.count = qty;
        orderProductEntity.album_thumb = productEntity.album_thumb;
        
        orderEntity.ID = order_num;
        orderEntity.total_amount = productEntity.sale_price;
        orderEntity.status = @"1";
        orderEntity.payWay = _payWay;
        orderEntity.ship_cost = productEntity.ship_cost;
        orderEntity.order_class = @"3";
        orderEntity.store_id = @"LY_ID";
        orderEntity.store_name = @"乐游山水网络科技有限公司";
    }else{
        if(lpEntity){
            orderProductEntity.product_class = @"2";
            orderProductEntity.product_id = lpEntity.ID;
            orderProductEntity.product_name = lpEntity.title;
            orderProductEntity.price = lpEntity.price;
            //    orderProductEntity.introduce = lpEntity.product_introduce;
            orderProductEntity.introduce = lpEntity.content;
            orderProductEntity.count = qty;
            orderProductEntity.album_thumb = lpEntity.album_thumb;
            
            orderEntity.ID = order_num;
            orderEntity.total_amount = lpEntity.price;
            orderEntity.status = @"1";
            orderEntity.payWay = _payWay;
            orderEntity.ship_cost = lpEntity.ship_cost;
            orderEntity.order_class = @"2";
            orderEntity.store_id = lpEntity.storeID;
            orderEntity.store_name = lpEntity.store_name;
        }else{
            orderProductEntity.product_class = @"1";
            orderProductEntity.product_id = tDetailsEntity.t_id;
            orderProductEntity.product_name = tDetailsEntity.t_name;
            orderProductEntity.price = tDetailsEntity.t_price;
            orderProductEntity.introduce = @"t_preview";
            orderProductEntity.count = qty;
            orderProductEntity.album_thumb = [tDetailsEntity.album_thumb substringFromIndex:25];
            
            orderEntity.ID = order_num;
            orderEntity.total_amount = tDetailsEntity.t_price;
            orderEntity.status = @"1";
            orderEntity.payWay = _payWay;
            orderEntity.ship_cost = @"0.00";
            orderEntity.order_class = @"1";
            orderEntity.store_id = tDetailsEntity.a_id;
            orderEntity.store_name = tDetailsEntity.a_name;
        }
    }
    
    NSDate * nowDate = [NSDate date];
    NSDateFormatter * dateFormat = [[NSDateFormatter alloc]init];
    //    dateFormat = @"yyyy年MM月dd日 HH:mm:SS";
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    orderEntity.insert_time = [dateFormat stringFromDate:nowDate];
    orderEntity.order_num = order_num;
    
    orderEntity.product_list = [[NSMutableArray alloc] init];
    [orderEntity.product_list addObject:orderProductEntity];
    
    //TODO: 保存订单号到本地
    NSUserDefaults *orderDefault = [NSUserDefaults standardUserDefaults];
    NSArray *arrTemp=[orderDefault objectForKey:@"OrderEntityList"];
    //可以用alloc 方法代替
    NSMutableArray *mutableArray=[NSMutableArray arrayWithArray:arrTemp];
    if([mutableArray count]>0){
        for(int i=0;i<[mutableArray count];i++){
            OrderEntity *orderEntityTemp = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArray objectAtIndex:i]];
            if([orderEntityTemp.order_class isEqualToString:orderEntity.order_class]){
                [mutableArray removeObjectAtIndex:i];
            }
        }
    }
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:orderEntity];
    [mutableArray addObject:data];
    //记住要转换成不可变数组类型
    NSArray * array = [NSArray arrayWithArray:mutableArray];
    [orderDefault setObject:array forKey:@"OrderEntityList"];
}

-(IBAction)btnAddressList:(id)sender{
    AddressViewController *vc = [[AddressViewController alloc]init];
    vc.orderEnsureViewController = self;
    vc.userEntity = userEntity;
    [self.navigationController pushViewController:vc animated:YES];
}

-(IBAction)btnTicketPersonList:(id)sender{
    TicketPersonViewController *vc = [[TicketPersonViewController alloc]init];
    vc.orderEnsureViewController = self;
    vc.userEntity = userEntity;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)getAddressDefault{
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           userEntity.userId, @"userid",nil];
    
    [service getNetWorkData:param
                       Path:USER_ADDRESS_DEFAULT
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      NSArray *array = [dic objectForKey:@"rows"];
                      for (NSDictionary* attributes in array) {
                          UserAddressEntity *addressEntity = [[UserAddressEntity alloc] init];
                          addressEntity = [addressEntity initWithAttributes:attributes];
                          [mutableArrayAddress addObject:addressEntity];
                      }
                      dispatch_async(dispatch_get_main_queue(), ^{
                          if([mutableArrayAddress count]>0) {
                              UserAddressEntity *addressEntity = [mutableArrayAddress objectAtIndex:0];
                              addName.text = addressEntity.addName;
                              addPhone.text = addressEntity.addPhone;
                              addressInfo.text = [NSString stringWithFormat:@"%@%@%@%@",addressEntity.pro_name,addressEntity.city_name,addressEntity.district,addressEntity.detailAddress];
                              _addressID =addressEntity.ID;
                          }else{
                              AddAddressViewController *vc = [[AddAddressViewController alloc]init];
                              vc.orderEnsureView = self;
                              [[self navigationController]pushViewController:vc animated:YES];
                          }
                      });
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}

-(void)handlePayResult:(id)code{
    OrderViewController *vc=[[OrderViewController alloc]init];
    vc.userId=userEntity.userId;
    if([code isKindOfClass:[NSString class]]){
        if([code isEqualToString:@"6001"]){
            ALERT_ERR_MSG(PayCanceled);
            vc.orderFlag=NO;
        }
        if([code isEqualToString:@"9000"]){
            ALERT_ERR_MSG(PaySuccess);
            vc.orderFlag=YES;
        }
    }else{
        if([[code valueForKey:@"object"] isEqualToString:@"6001"]){
            ALERT_ERR_MSG(PayCanceled);
            vc.orderFlag=NO;
        }
        if([[code valueForKey:@"object"] isEqualToString:@"9000"]){
            ALERT_ERR_MSG(PaySuccess);
            vc.orderFlag=YES;
        }
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"OrderEnsureViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"OrderEnsureViewController"];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];//移除通知
}

-(IBAction)btnPlusAction:(id)sender{
    if(productEntity){
        labQty2.text = [NSString stringWithFormat:@"%d",[labQty2.text intValue]+1];
        total2.text = [NSString stringWithFormat:@"%.2f",[total2.text floatValue]+[productEntity.sale_price floatValue]];
    }else{
        labQty.text = [NSString stringWithFormat:@"%d",[labQty.text intValue]+1];
        if(lpEntity)
            total.text = [NSString stringWithFormat:@"%.2f",[total.text floatValue]+[lpEntity.price floatValue]];
        else
            total.text = [NSString stringWithFormat:@"%.2f",[total.text floatValue]+1.00f];
    }
}
-(IBAction)btnMinusAction:(id)sender{
    if(productEntity){
        if(([labQty2.text intValue]-1)>0){
            labQty2.text = [NSString stringWithFormat:@"%d",[labQty2.text intValue]-1];
            total2.text = [NSString stringWithFormat:@"%.2f",[total2.text floatValue]-[productEntity.sale_price intValue]];
        }
    }else{
        if(([labQty.text intValue]-1)>0){

            labQty.text = [NSString stringWithFormat:@"%d",[labQty.text intValue]-1];
            if(lpEntity)
                total.text = [NSString stringWithFormat:@"%.2f",[total.text floatValue]-[lpEntity.price floatValue]];
            else
                total.text = [NSString stringWithFormat:@"%.2f",[total.text floatValue]-1.00f];
            if ([self.couponModel.limit_money floatValue] > ([self.total.text floatValue] + [self.couponModel.money floatValue])) {
                self.total.text = [NSString stringWithFormat:@"%.2f",[total.text floatValue] + [self.couponModel.money floatValue]];
                self.couponModel = nil;
                self.couponNum.text = @"";
            }
        }
    }
}

- (IBAction)couponClick:(id)sender
{
    CouponViewController *mvc = [[CouponViewController alloc]init];
    mvc.product_class_id = [NSString stringWithFormat:@"%@",lpEntity.product_class_id];
    mvc.product_id = lpEntity.ID;
    mvc.order_total_amount = [NSString stringWithFormat:@"%f",[lpEntity.price floatValue]*[labQty.text intValue]];
    mvc.needNoUseBtn = YES;
    [mvc setBlock:^(CouponModel *model)
    {
        self.couponNum.text = model.money;
        self.couponModel = model;
        total.text = [NSString stringWithFormat:@"%.2f",[lpEntity.price floatValue]*[labQty.text intValue]- [model.money floatValue]];
    }];
    [self.navigationController pushViewController:mvc animated:YES];
}

-(IBAction)ticketIntroduce:(id)sender{
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = productEntity.product_introduce;
    vc.vcTitle = @"票型说明";
    [self.navigationController pushViewController:vc animated:YES];
}
@end
